const staticCacheName = "site-static-V5"
const dynamicCacheName = "site-dynamic-V5"
const assets = [
  '/', // index.html
  '/index.html', // index.html
  '/js/app.js',
  '/js/ui.js',
  '/js/materialize.min.js',
  '/css/styles.css',
  '/css/fonts.css',
  '/css/materialize.min.css',
  '/img/dish.png',
  'https://fonts.gstatic.com/s/materialicons/v143/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2',
  '/pages/unreachable.html'
]

// cache size limit function
function limitCacheSize(name, size) {
  caches.open(name).then(cache => {
    cache.keys().then(keys => {
      if(keys.length > size) {
        cache.delete(keys[0]).then(limitCatchSize(name, size))
      }
    })
  })
}
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(staticCacheName).then((cache) => {
      cache.addAll(assets)
    })
  )
})

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then(keys => {
      return Promise.all(
        keys.map(key => {
          // 清理缓存
          if ((staticCacheName !== key) && (dynamicCacheName !== key)) {
            return caches.delete(key);
          }
        })
      )
    }).then(() => {
      console.log('cache deleted');
    })
  )
})

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((res) => {
      if(res) {
        return res
      } else {
        return fetch(event.request).then(fetchRes => {
          return caches.open(dynamicCacheName).then((cache) => {
            cache.put(event.request.url, fetchRes.clone())
            limitCacheSize(dynamicCacheName, 100)
            return fetchRes
          })
        })
      }
    }).catch((err) => {
      // 在离线模式下，去未缓存的页面，就给一个不能打开的反馈
      if(event.request.url.includes(".html")) {
        return caches.match('/pages/unreachable.html')
      }
    })
  )
})